package com.junxonline.plat.service.menu.impl;

import com.junxonline.common.dao.model.Menu;
import com.junxonline.common.dao.model.Role;
import com.junxonline.common.dao.model.User;
import com.junxonline.common.dao.pojo.JsTree;
import com.junxonline.common.dao.pojo.JsTreeState;
import com.junxonline.common.dao.repository.MenuRepository;
import com.junxonline.common.dao.vo.MenuVO;
import com.junxonline.common.dao.vo.QueryMenuVO;
import com.junxonline.common.util.CommonUtils;
import com.junxonline.plat.service.base.impl.BaseServiceImpl;
import com.junxonline.plat.service.menu.MenuService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Transactional
public class MenuServiceImpl extends BaseServiceImpl implements MenuService {

    private Logger logger = LogManager.getLogger();

    @Autowired
    private MenuRepository menuRepository;

    /**
     * 获取导航菜单数据
     *
     * @param userId
     * @return
     */
    @Override
    public List<Menu> getNavMenu(Long userId) {

        User user = getUser(userId);

        List<Role> roles = user.getRoles();
        List<Menu> menus = new ArrayList<>();

        for (Role role : roles) {
            menus.addAll(menuRepository.findMenusByRoleIdOrderByMenuSortAsc(role.getRoleId()));
        }

        // 去重
        Set<Menu> set = new HashSet<>();
        List<Menu> returnMenus = new ArrayList<>();
        Iterator<Menu> iterator = menus.iterator();
        while (iterator.hasNext()) {
            Menu menu = iterator.next();
            if (set.add(menu)) {
                returnMenus.add(menu);
            }
        }

        // 删除所有的按钮和数据接口
        iterator = returnMenus.iterator();
        while (iterator.hasNext()) {
            Menu menu = iterator.next();
            if (menu.getMenuType().equals(2) || menu.getMenuType().equals(3)) {
                iterator.remove();
            }
        }

        return returnMenus;
    }

    /**
     * 获取按钮数据
     *
     * @param menuUrl
     * @param userId
     * @return
     */
    @Override
    public List<Menu> getButton(String menuUrl, Long userId) {

        User user = getUser(userId);

        List<Role> roles = user.getRoles();
        List<Menu> menus = new ArrayList<>();
        List<Menu> returnButtons = new ArrayList<>();

        Menu parentMenu = menuRepository.findByMenuUrl(menuUrl);

        if (CommonUtils.isNotEmpty(parentMenu)) {

            for (Role role : roles) {
                menus.addAll(menuRepository.findMenusByRoleIdOrderByMenuSortAsc(role.getRoleId()));
            }

            // 去重
            Set<Menu> set = new HashSet<Menu>();
            Iterator<Menu> iterator = menus.iterator();
            while (iterator.hasNext()) {
                Menu menu = iterator.next();
                if (set.add(menu)) {
                    returnButtons.add(menu);
                }
            }

            iterator = returnButtons.iterator();
            while (iterator.hasNext()) {
                Menu menu = iterator.next();
                if (menu.getMenuType().intValue() != 2 || menu.getMenuParentId() == null ||
                        !menu.getMenuParentId().equals(parentMenu.getMenuId().toString())) {
                    iterator.remove();
                }
            }

        }

        return returnButtons;
    }

    /**
     * 获取菜单树数据
     *
     * @return
     */
    @Override
    public List<JsTree> getMenuTree() {

        List<JsTree> jsTrees = new ArrayList<>();

        // 获取所有的菜单数据
        List<Menu> menus = menuRepository.findAll(new Sort(Sort.Direction.ASC, "menuSort"));

        // 构建菜单树
        for (Menu menu : menus) {
            JsTree jsTree = new JsTree();
            jsTree.setId(menu.getMenuId().toString());
            jsTree.setText(menu.getMenuName());

            // 为顶级菜单设置父级Id为# （JsTree数据规范）
            if (CommonUtils.isEmpty(menu.getMenuParentId())) {
                jsTree.setParent("#");
            }
            else {
                jsTree.setParent(menu.getMenuParentId());
            }


            // 为按钮设置图标
            if (menu.getMenuType().equals(2)) {
                jsTree.setIcon("fa fa-file icon-state-warning");
            }
            // 为数据接口设置图标
            else if (menu.getMenuType().equals(3)) {
                jsTree.setIcon("fa fa-leaf icon-state-success");
            }

            // 为顶级菜单设置默认展开
            if (CommonUtils.isEmpty(menu.getMenuParentId())) {
                jsTree.setState(new JsTreeState(true, false, false));
            }
            // 为非顶级菜单组设置默认不展开
            else {
                jsTree.setState(new JsTreeState(false, false, false));
            }


            jsTrees.add(jsTree);
        }

        return jsTrees;
    }

    /**
     * 获取菜单数据
     *
     * @param vo
     * @return
     */
    @Override
    public Map<String, Object> getMenu(QueryMenuVO vo) {
        return null;
    }

    /**
     * 获取菜单的所有子菜单
     *
     * @param menuId
     * @return
     */
    @Override
    public Map<String, Object> getMenuChildren(Long menuId) {
        return null;
    }

    /**
     * 添加菜单
     *
     * @param vo
     * @return
     */
    @Override
    public Menu addMenu(MenuVO vo) {
        return null;
    }
}
